/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PanelCadastroUsuario.java
 *
 * Created on 17/09/2011, 18:06:51
 */
package modules.enderecamento.gui.jpanel;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.table.DefaultTableModel;
import modules.enderecamento.facade.WMSFacade;
import modules.enderecamento.gui.custom.WMSJCheckBox;
import modules.enderecamento.models.dto.Cargo;
import modules.enderecamento.models.dto.GruposAcesso;
import modules.enderecamento.models.dto.GruposAcessosUsuario;
import modules.enderecamento.models.dto.Usuario;
import modules.enderecamento.models.dto.Permissao;
import modules.enderecamento.security.WMSSession;
import modules.enderecamento.util.BoxPanel;

/**
 *
 * @author Clezio
 */
public class PanelCadastroUsuario extends javax.swing.JPanel {

    private WMSFacade wmsFacade;
    private boolean permissaoAdicionarGlobal;
    /** Creates new form PanelCadastroUsuario */
    public PanelCadastroUsuario() {
        initComponents();
        wmsFacade = new WMSFacade();
        checaPermissao();
    }

//    @Override
//     protected void paintComponent(Graphics g) {
//         super.paintComponent(g);
//         if (getImageFundo() != null){
//             g.drawImage(getImageFundo(), 0, 0, getWidth(), getHeight(), this);
//         }
//     }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        tfId = new modules.enderecamento.gui.custom.WMSJTextField();
        lbId = new modules.enderecamento.gui.custom.WMSLabel();
        lbNome = new modules.enderecamento.gui.custom.WMSLabel();
        tfNome = new modules.enderecamento.gui.custom.WMSJTextField();
        btnSalvar = new modules.enderecamento.gui.custom.WMSJButton();
        btnNovo = new modules.enderecamento.gui.custom.WMSJButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new modules.enderecamento.gui.custom.WMSJTable();
        btnAlterar = new modules.enderecamento.gui.custom.WMSJButton();
        btnExcluir = new modules.enderecamento.gui.custom.WMSJButton();
        lbGruposAcessos = new modules.enderecamento.gui.custom.WMSLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jPanelCheckBox = new javax.swing.JPanel();
        lbSenha = new modules.enderecamento.gui.custom.WMSLabel();
        tfSenha = new modules.enderecamento.gui.custom.WMSJPasswordField();
        tfSenhaConfirmar = new modules.enderecamento.gui.custom.WMSJPasswordField();
        lbConfirmarSenha = new modules.enderecamento.gui.custom.WMSLabel();
        lbLogin = new modules.enderecamento.gui.custom.WMSLabel();
        tfLogin = new javax.swing.JTextField();
        cbCargos = new modules.enderecamento.gui.custom.WMSJComboBox();
        lbCargo = new modules.enderecamento.gui.custom.WMSLabel();

        setBackground(new java.awt.Color(238, 238, 238));
        addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                formAncestorAdded(evt);
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Cadastro de Usuário");

        tfId.setEditable(false);
        tfId.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfIdKeyPressed(evt);
            }
        });

        lbId.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbId.setText("ID:");

        lbNome.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbNome.setText("Nome:");

        tfNome.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfNomeKeyPressed(evt);
            }
        });

        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnNovo.setText("Novo");
        btnNovo.setEnabled(false);
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null}
            },
            new String [] {
                "ID", "Nome", "Login"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        btnAlterar.setText("Alterar");
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });

        btnExcluir.setText("Excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        lbGruposAcessos.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbGruposAcessos.setText("Grupos Acessos:");

        jScrollPane2.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane2.setMaximumSize(new java.awt.Dimension(259, 300));
        jScrollPane2.setPreferredSize(new java.awt.Dimension(259, 100));

        jPanelCheckBox.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jPanelCheckBoxMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanelCheckBoxLayout = new javax.swing.GroupLayout(jPanelCheckBox);
        jPanelCheckBox.setLayout(jPanelCheckBoxLayout);
        jPanelCheckBoxLayout.setHorizontalGroup(
            jPanelCheckBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 462, Short.MAX_VALUE)
        );
        jPanelCheckBoxLayout.setVerticalGroup(
            jPanelCheckBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 567, Short.MAX_VALUE)
        );

        jScrollPane2.setViewportView(jPanelCheckBox);

        lbSenha.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbSenha.setText("Senha:");

        tfSenha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfSenhaActionPerformed(evt);
            }
        });
        tfSenha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfSenhaKeyPressed(evt);
            }
        });

        tfSenhaConfirmar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfSenhaConfirmarActionPerformed(evt);
            }
        });
        tfSenhaConfirmar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfSenhaConfirmarKeyPressed(evt);
            }
        });

        lbConfirmarSenha.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbConfirmarSenha.setText("Confirmar Senha:");

        lbLogin.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbLogin.setText("Login:");
        lbLogin.setMaximumSize(new java.awt.Dimension(15, 14));
        lbLogin.setMinimumSize(new java.awt.Dimension(15, 14));
        lbLogin.setPreferredSize(new java.awt.Dimension(15, 14));

        tfLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfLoginActionPerformed(evt);
            }
        });
        tfLogin.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfLoginKeyPressed(evt);
            }
        });

        cbCargos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione" }));

        lbCargo.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbCargo.setText("Cargo:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 817, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lbNome, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lbSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(lbConfirmarSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(lbCargo, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(lbGruposAcessos, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(7, 7, 7)
                                .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(244, 244, 244)
                                .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(17, 17, 17)
                                .addComponent(btnAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(tfSenhaConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cbCargos, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 398, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(lbId, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lbLogin, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(tfId, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(tfLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(229, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(42, 42, 42)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbId, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbNome, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfSenhaConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbConfirmarSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbCargos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbCargo, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lbGruposAcessos, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void tfIdKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfIdKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            save();
        }
}//GEN-LAST:event_tfIdKeyPressed

    private void tfNomeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfNomeKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfSenha.requestFocus();
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfNome.setText("");
            tfLogin.requestFocus();
        }
}//GEN-LAST:event_tfNomeKeyPressed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        save();
}//GEN-LAST:event_btnSalvarActionPerformed

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        clearFields();
        btnNovo.setEnabled(false);
}//GEN-LAST:event_btnNovoActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        if (jTable1.getSelectedRowCount() > 0) {
            DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
            int selected = jTable1.getSelectedRow();
            int id = (Integer) modelo.getValueAt(selected, 0);
            Usuario usuario = wmsFacade.obterUsuarioById(id);
            if (usuario != null) {
                tfId.setText("" + usuario.getId());
                tfNome.setText(usuario.getNome());
                tfLogin.setText(usuario.getLogin());
                tfSenha.setText(usuario.getSenha());
                tfSenhaConfirmar.setText(usuario.getSenha());
                btnNovo.setEnabled(true);
                criarCheckGruposAcessos(wmsFacade.obterGruposAcessos("from GruposAcesso order by nome"),
                        usuario.getGruposAcessosUsuarioses());
                //Set Cargo
                cbCargos.setSelectedIndex(0);
                for (int i = 0; i < cbCargos.getItemCount(); i++) {
                    try{
                        Cargo cbObj = (Cargo) cbCargos.getItemAt(i);
                        if(usuario.getCargo() != null){
                            if(cbObj.getId() == usuario.getCargo().getId()){
                                cbCargos.setSelectedIndex(i);
                                break;
                            }
                        }
                    }catch(Exception e){}
                }
            }
        } else {
            BoxPanel.showMessageDialog(null, "Selecione um Usuário");
        }
}//GEN-LAST:event_btnAlterarActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        excluir();
}//GEN-LAST:event_btnExcluirActionPerformed

    private void formAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_formAncestorAdded
        listarUsuarios(wmsFacade.obterUsuarios("from Usuario order by nome"));
        criarCheckGruposAcessos(wmsFacade.obterGruposAcessos("from GruposAcesso order by nome"), new HashSet<GruposAcessosUsuario>());
        clearFields();
        preencheCbCargos(wmsFacade.obterCargos("from Cargo order by nome"));
    }//GEN-LAST:event_formAncestorAdded

    private void tfLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfLoginActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfLoginActionPerformed

    private void tfLoginKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfLoginKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfNome.requestFocus();
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfLogin.setText("");
        }
    }//GEN-LAST:event_tfLoginKeyPressed

    private void tfSenhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfSenhaKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfSenhaConfirmar.requestFocus();
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfSenha.setText("");
            tfNome.requestFocus();
        }
    }//GEN-LAST:event_tfSenhaKeyPressed

    private void tfSenhaConfirmarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfSenhaConfirmarKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            if (jPanelCheckBox.getComponentCount() > 0) {
                jPanelCheckBox.getComponent(0).requestFocus();
            }
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfSenhaConfirmar.setText("");
            tfSenha.requestFocus();
        }
    }//GEN-LAST:event_tfSenhaConfirmarKeyPressed

    private void tfSenhaConfirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfSenhaConfirmarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfSenhaConfirmarActionPerformed

    private void jPanelCheckBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanelCheckBoxMouseClicked
        
    }//GEN-LAST:event_jPanelCheckBoxMouseClicked

    private void tfSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfSenhaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfSenhaActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private modules.enderecamento.gui.custom.WMSJButton btnAlterar;
    private modules.enderecamento.gui.custom.WMSJButton btnExcluir;
    private modules.enderecamento.gui.custom.WMSJButton btnNovo;
    private modules.enderecamento.gui.custom.WMSJButton btnSalvar;
    private modules.enderecamento.gui.custom.WMSJComboBox cbCargos;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanelCheckBox;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private modules.enderecamento.gui.custom.WMSJTable jTable1;
    private modules.enderecamento.gui.custom.WMSLabel lbCargo;
    private modules.enderecamento.gui.custom.WMSLabel lbConfirmarSenha;
    private modules.enderecamento.gui.custom.WMSLabel lbGruposAcessos;
    private modules.enderecamento.gui.custom.WMSLabel lbId;
    private modules.enderecamento.gui.custom.WMSLabel lbLogin;
    private modules.enderecamento.gui.custom.WMSLabel lbNome;
    private modules.enderecamento.gui.custom.WMSLabel lbSenha;
    private modules.enderecamento.gui.custom.WMSJTextField tfId;
    private javax.swing.JTextField tfLogin;
    private modules.enderecamento.gui.custom.WMSJTextField tfNome;
    private modules.enderecamento.gui.custom.WMSJPasswordField tfSenha;
    private modules.enderecamento.gui.custom.WMSJPasswordField tfSenhaConfirmar;
    // End of variables declaration//GEN-END:variables

    private void clearFields() {
        tfId.setText("");
        tfNome.setText("");
        tfLogin.setText("");
        tfSenha.setText("");
        tfSenhaConfirmar.setText("");
        tfLogin.requestFocus();
        cbCargos.setSelectedIndex(0);
        criarCheckGruposAcessos(wmsFacade.obterGruposAcessos("from GruposAcesso order by nome"), new HashSet<GruposAcessosUsuario>());
    }

    private void listarUsuarios(List<Usuario> Usuarios) {
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(1);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(300);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(100);

        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        modelo.setNumRows(0);

        for (int i = 0; i < Usuarios.size(); i++) {
            int id = Usuarios.get(i).getId();
            String nome = Usuarios.get(i).getNome();
            String login = Usuarios.get(i).getLogin();
            modelo.addRow(new Object[]{
                        id, nome, login
                    });
        }
    }

    private void save() {
        //Checa permissao
        if (tfId.getText().length() == 0 && !permissaoAdicionarGlobal) {
            BoxPanel.showMessageDialog(null, "Usuário sem permissão para adicionar novo registro.");
            return;
        }
        if (!tfSenha.getText().equals(tfSenhaConfirmar.getText())) {
            BoxPanel.showMessageDialog(null, "O valor digitado no campo senha é diferente do confirmar senha.");
            return;
        }
        Usuario obj = new Usuario();
        obj.setNome(tfNome.getText());
        obj.setCargo((Cargo) cbCargos.getSelectedItem());
        obj.setLogin(tfLogin.getText());
        obj.setSenha(tfSenha.getText());
        obj.setAtivo(true);
        if (tfId.getText().length() > 0) {
            obj.setId(Integer.parseInt(tfId.getText()));
        }

        Set<GruposAcessosUsuario> gruposAcessoUsuario = obterGruposAcessosSelecionadas(obj);
        obj.setGruposAcessosUsuarioses(gruposAcessoUsuario);

        if (wmsFacade.saveUsuario(obj)) {
            clearFields();
            listarUsuarios(wmsFacade.obterUsuarios("from Usuario order by nome"));
            btnNovo.setEnabled(false);
            BoxPanel.showMessageDialog(null, "Usuário salvo com sucesso.");
        }
    }

    private void excluir() {
        if (jTable1.getSelectedRowCount() > 0) {
            DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
            int[] selected = jTable1.getSelectedRows();
            for (int i = 0; i < selected.length; i++) {
                int id = (Integer) modelo.getValueAt(selected[i], 0);
                wmsFacade.deleteUsuario(wmsFacade.obterUsuarioById(id));
                modelo.removeRow(jTable1.getSelectedRow());
            }
            listarUsuarios(wmsFacade.obterUsuarios("from Usuario order by nome"));
        } else {
            BoxPanel.showMessageDialog(null, "Selecione um Usuário");
        }
    }

    private Set<GruposAcessosUsuario> obterGruposAcessosSelecionadas(Usuario grupoAcesso) {
        Set<GruposAcessosUsuario> gruposAcessosUsuarios = new HashSet<GruposAcessosUsuario>();
        for (int i = 0; i < jPanelCheckBox.getComponentCount(); i++) {
            WMSJCheckBox wMSJCheckBox = (WMSJCheckBox) jPanelCheckBox.getComponent(i);
            if (wMSJCheckBox.isSelected()) {
                GruposAcessosUsuario gruposAcessosUsuario = new GruposAcessosUsuario();
                GruposAcesso gruposAcesso = (GruposAcesso) wMSJCheckBox.getObj();
                gruposAcessosUsuario.setGruposAcessos(gruposAcesso);
                gruposAcessosUsuario.setUsuarios(grupoAcesso);
                gruposAcessosUsuarios.add(gruposAcessosUsuario);
            }
        }
        return gruposAcessosUsuarios;
    }

    private void criarCheckGruposAcessos(List<GruposAcesso> gruposAcessos, Set selecteds) {
        int posY = 5;
        if (gruposAcessos != null) {
            jPanelCheckBox.removeAll();
            jPanelCheckBox.repaint();
            for (int i = 0; i < gruposAcessos.size(); i++) {
                boolean selected = false;
                Iterator it = selecteds.iterator();
                while (it.hasNext()) {
                    GruposAcessosUsuario gruposAcessosUsuario = (GruposAcessosUsuario) it.next();
                    GruposAcesso gruposAcesso = gruposAcessosUsuario.getGruposAcessos();
                    if (gruposAcesso.getId() == gruposAcessos.get(i).getId()) {
                        selected = true;
                        break;
                    }
                }
                WMSJCheckBox cb = new WMSJCheckBox(gruposAcessos.get(i), selected);
                cb.addKeyListener(new java.awt.event.KeyAdapter() {

                    public void keyPressed(java.awt.event.KeyEvent evt) {
                        if (evt.getKeyCode() == evt.VK_ENTER) {
                            save();
                        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
                            tfSenhaConfirmar.requestFocus();
                        }
                    }
                });
                cb.setBounds(5, posY, 300, 20);
                jPanelCheckBox.add(cb);
                if(jPanelCheckBox.getComponentCount() > 13){
                    jPanelCheckBox.setPreferredSize(new Dimension(259, (int) (jPanelCheckBox.getPreferredSize().getHeight() + 9)));
                }
                posY += 20;
            }
        }
    }

    private void checaPermissao(){
        permissaoAdicionarGlobal = true;
        Map<Integer,Permissao> mapPermissoes = WMSSession.getInstance().getMapPermissoes();
        boolean permissaoAlterar = mapPermissoes.containsKey(27);
        boolean permissaoExcluir = mapPermissoes.containsKey(28);
        boolean permissaoAdicionar = mapPermissoes.containsKey(26);

        if(!permissaoAlterar){btnAlterar.setVisible(false);}
        if(!permissaoExcluir){btnExcluir.setVisible(false);}
        if(!permissaoAdicionar && !permissaoAlterar){
            ocultarCamposFormulario();
        }else if(!permissaoAdicionar){
            btnNovo.setVisible(false);
            permissaoAdicionarGlobal = false;
        }
    }

    private void ocultarCamposFormulario() {
        //oculta do formulário
        lbId.setVisible(false);
        lbLogin.setVisible(false);
        lbNome.setVisible(false);
        lbSenha.setVisible(false);
        lbConfirmarSenha.setVisible(false);
        lbGruposAcessos.setVisible(false);
        lbCargo.setVisible(false);

        tfId.setVisible(false);
        tfLogin.setVisible(false);
        tfNome.setVisible(false);
        tfSenha.setVisible(false);
        tfSenhaConfirmar.setVisible(false);
        cbCargos.setVisible(false);

        btnSalvar.setVisible(false);
        btnNovo.setVisible(false);
        jScrollPane2.setVisible(false);
    }

    private void preencheCbCargos(List<Cargo> lista){
        cbCargos.removeAllItems();
        cbCargos.addItem("Selecione");
        for (int i= 0; i < lista.size(); i++) {
            cbCargos.addItem(lista.get(i));
        }
    }
}
